import validate from 'utils/formCheck'
//定义一个缓存
var _cache = {}
/**
 * 获取用户浏览器UA
 */
const getUa = function () {
  if (_cache.ua) {
    return _cache.ua
  }

  var ua = window.navigator.userAgent.toLocaleLowerCase()
  var isMobile = !!ua.match(/AppleWebKit.*Mobile.*/i)
  var isApple = !!ua.match(/(ipad|iphone|ipod|mac)/i)
  var isAndroid = !!ua.match(/android/i)
  var isUc = !!ua.match(/ucbrowser/i)
  var isWeixin = !!ua.match(/micromessenger/i)
  var isQQ = !!ua.match(/pa qq/i)
  var isWeibo = !!ua.match(/weiBo/i)

  _cache.ua = {
    isMobile: isMobile,
    isApple: isApple,
    isAndroid: isAndroid,
    isUc: isUc,
    isWeixin: isWeixin,
    isQQ: isQQ,
    isWeibo: isWeibo
  }
  return _cache.ua
}

const isMobile = function () {
  let flag = navigator.userAgent.match(
    /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
  )
  return flag
}

/**
 * uView的防抖,名字是暂时的，升级版本再换回来
 * 防抖原理：一定时间内，只有最后一次操作，再过wait毫秒后才执行函数
 * 
 * @param {Function} func 要执行的回调函数 
 * @param {Number} wait 延时的时间
 * @param {Boolean} immediate 是否立即执行 
 * @return null
 */
let timeout = null;
function uDebounce(func, wait = 500, immediate = false) {
	// 清除定时器
	if (timeout !== null) clearTimeout(timeout);
	// 立即执行，此类情况一般用不到
	if (immediate) {
		var callNow = !timeout;
		timeout = setTimeout(function() {
			timeout = null;
		}, wait);
		if (callNow) typeof func === 'function' && func();
	} else {
		// 设置定时器，当最后一次操作后，timeout不会再被清除，所以在延时wait毫秒后执行func回调方法
		timeout = setTimeout(function() {
			typeof func === 'function' && func();
		}, wait);
	}
}

let timer, flag;
function uThrottle(func, wait = 500, immediate = true) {
	if (immediate) {
		if (!flag) {
			flag = true;
			// 如果是立即执行，则在wait毫秒内开始时执行
			typeof func === 'function' && func();
			timer = setTimeout(() => {
				flag = false;
			}, wait);
		}
	} else {
		if (!flag) {
			flag = true
			// 如果是非立即执行，则在wait毫秒内的结束处执行
			timer = setTimeout(() => {
				flag = false
				typeof func === 'function' && func();
			}, wait);
		}
		
	}
};
/* 防抖
 *@param fn {Function}   实际要执行的函数
 * @param delay {Number}  延迟时间，也就是阈值，单位是毫秒（ms）
 * @return {Function}     返回一个“去弹跳”了的函数
 * 用法：import { debounce } from '@/utils/utils.js';
 *       sure:debounce(function(){}),//备注，不能用箭头函数()=>，不然里面的this不对
 */
const debounce = function (fn, time = 250) {
  let timerId = null
  return function () {
    const that = this
    const args = arguments
    timerId && clearTimeout(timerId)
    timerId = setTimeout(() => {
      fn.apply(that, args)
    }, time)
  }
}

const throttle = function (fn, time = 250) {
  let last, timerId
  return function () {
    const that = this
    const args = arguments
    const now = Date.now()
    if (last && now - last < time) {
      timerId && clearTimeout(timerId)
      timerId = setTimeout(() => {
        fn.apply(that, args)
      }, time)
    } else {
      last = now
      fn.apply(that, args)
    }
  }
}

const isMiniProgram = function () {
  return new Promise((resolve, reject) => {
    if (getUa().isWeixin) {
      if (wx && wx.miniProgram) {
        wx.miniProgram.getEnv(function (res) {
          if (res.miniprogram) {
            resolve('WX_MINIAPP_USER_LIVE')
            // sourceChannel = 'WX_MINIAPP_USER_LIVE'
            // alert(1)
          } else {
            resolve('WX_MALL')
            // sourceChannel = 'WX_MALL'
            // alert(2)
          }
        })
      }
    } else {
      resolve('H5_MALL')
      // sourceChannel = 'H5_MALL'
    }
  })

  // let sourceChannel = 'H5_MALL'

  // return sourceChannel
}

const getUrlKey = function (name) {
  return (
    decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(decodeURIComponent(location.href)) || [, ''])[1].replace(/\+/g, '%20')) || null
  )
}

function colorRgb(sColor) {
  if (sColor) {
    sColor = sColor.toLowerCase()
  }
  // 十六进制颜色值的正则表达式
  var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/
  // 如果是16进制颜色
  if (sColor && reg.test(sColor)) {
    if (sColor.length === 4) {
      var sColorNew = '#'
      for (var i = 1; i < 4; i += 1) {
        sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1))
      }
      sColor = sColorNew
    }
    // 处理六位的颜色值
    var sColorChange = []
    for (var i = 1; i < sColor.length; i += 2) {
      sColorChange.push(parseInt('0x' + sColor.slice(i, i + 2)))
    }

    return {
      r: sColorChange[0],
      g: sColorChange[1],
      b: sColorChange[2]
    }
  }
  return {}
}

function goLoginPage(that) {
    if (getUa().isWeixin) {// 如果是微信浏览器
        that.$router.replace({ path: '/loginWechat', query: { redirect: that.$route.fullPath } })
    } else{
		that.$router.replace({ path: '/login', query: { redirect: that.$route.fullPath } })
	}
}

// 数据效验
const test = {
    isEmpty(val) {
        // null or undefined
        if (val == null) return true
		
		if (val === 'undefined') return true
		
        if (typeof val === 'boolean') return false

        if (typeof val === 'number') return !val
		

        if (val instanceof Error) return val.message === ''

        switch (Object.prototype.toString.call(val)) {
            // String or Array
            case '[object String]':
            case '[object Array]':
                return !val.length

            // Map or Set or File
            case '[object File]':
            case '[object Map]':
            case '[object Set]': {
                return !val.size
            }
            // Plain Object
            case '[object Object]': {
                return !Object.keys(val).length
            }
        }
        return false
    },
    /**
     * 是否json字符串
     */
    jsonString(value) {
        if (typeof value == 'string') {
            try {
                var obj = JSON.parse(value)
                if (typeof obj == 'object' && obj) {
                    return true
                } else {
                    return false
                }
            } catch (e) {
                return false
            }
        }
        return false
    }
}

// text 要传文本
// digits 默认是2位小数点
function cash(text = 0, digits=2) {
    if(!text) {
      text = 0
    }
    if(!(text instanceof Number)){
      text = Number(text);
    }

    text = (text.toFixed(digits)).toString()
    if (text.indexOf(".") == -1) {
        text = text + '.00'
    }
    return text.indexOf(".") != -1 ? text.split(".") : text.join('');
}

export { getUa, isMobile, debounce, uDebounce, uThrottle, throttle, isMiniProgram, getUrlKey, colorRgb, test, goLoginPage, cash, validate }
export default { getUa, isMobile, debounce, uDebounce, uThrottle, throttle, isMiniProgram, getUrlKey, colorRgb, test, goLoginPage, cash, validate }
